/**
 * 
 */
package TextEditor;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;

import org.junit.runner.manipulation.Filter;

/**
 * Class encapsulating file operations: new, open, save
 * @author Yij_Zha
 */
public class FileOperation {

	/**
	 * 
	 */
	private EditorWindow editorWindow;
	/**
	 *  Constants for current file save status:
	 * 	FILESAVED 	 	means file saved success.
	 *  NOSAVEFILE 		means user discard the changed file.
	 *  SAVECANCELED 	means user discard this save and other operation cause save operation.User return to the original file status.
	 *  
	 */
	private final static int FILESAVED = 1;
	private final static int SAVECANCELED = -1;
	private final static int NOSAVEFILE = 0;
	
	FileChooserFunction fChooser = new FileChooserFunction();
	
	public FileOperation(EditorWindow editorWindow) {
		this.editorWindow = editorWindow;
	}
	/**
	 * Method checks whether the file is saved, exist but not saved, or new
	 * @return codename of the saved state of file. 
	 */
	public int checkSaveFile(){
		
		editorWindow.textArea.requestFocusInWindow();
		if(editorWindow.isModified()) 
		{	
			int saveChoose = JOptionPane.showConfirmDialog(editorWindow,"File is not saved,Do you want save it?",
					"Information:",JOptionPane.YES_NO_CANCEL_OPTION);
			
			
			if(saveChoose == JOptionPane.YES_OPTION)
			{
				if (editorWindow.isNewFile()){
					JFileChooser fileChooser = new JFileChooser();
					fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
					fileChooser.setDialogTitle("Save as");
					
					int result = fileChooser.showSaveDialog(editorWindow);
					if(result == JFileChooser.CANCEL_OPTION)
					{	
						editorWindow.infoStatus.setText("Save file had been canceled.");
						return SAVECANCELED;
					}
				}
				if(fileSave(false)) 		
					return FILESAVED;
				else 
					return NOSAVEFILE ;
				
			}
			else if(saveChoose == JOptionPane.NO_OPTION)
			{	
				editorWindow.infoStatus.setText("File did not saved.");
				return NOSAVEFILE;
			}
			else if(saveChoose == JOptionPane.CANCEL_OPTION)
			{	
				return SAVECANCELED;
			}
		}

		return FILESAVED;
	}
/**
 * Method performing saving operation
 * @param isSaveAs boolean parameter telling whether we need to save to a new file or to existing file
 * @return whether file is saved or cancelled to save
 */
	public boolean fileSave(boolean isSaveAs){

		File file;
		
		if( isSaveAs || editorWindow.isNewFile()){
			JFileChooser fileChooser = new JFileChooser();
			fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
			fileChooser.setSelectedFile(new File("default.txt"));
			fileChooser.setDialogTitle("Save As");
			
			FileFilter fileFilter = fChooser.createFileFilter("Text Files",
                    true, "txt");
			fileChooser.setFileFilter(fileFilter);

			int result = fileChooser.showSaveDialog(editorWindow);
			if(result == JFileChooser.CANCEL_OPTION)
			{	
				editorWindow.infoStatus.setText(" Save file canceled.");
				return false;
			}
			
			file = fileChooser.getSelectedFile();	
			//check file is exist or not, give warning whether overwrite it
			if(file.exists()){
				int choose = JOptionPane.showConfirmDialog
				(editorWindow,"File is exist,Do you want overwrite it ?", "Save information",JOptionPane.YES_NO_OPTION);
				if (choose == JOptionPane.NO_OPTION){
					return false;
				}
			}
			
		}
		else{
			file = editorWindow.getCurrentFile();			
		}

		BufferedWriter bfw;
		try {
			bfw = new BufferedWriter(new FileWriter(file));
			bfw.write(editorWindow.textArea.getText(),0,editorWindow.textArea.getText().length());
			bfw.flush();
			bfw.close();
		} catch (IOException e1) {
			e1.printStackTrace();
		}

		editorWindow.setNewFile(false);
		editorWindow.setCurrentFile(file);
		editorWindow.setModified(false);
		editorWindow.setTitle(file.getName() + " Collaborative TextEditor. Group 4. Soen 6441");
		editorWindow.infoStatus.setText(" Current Openning file is " + file.getAbsoluteFile());

		return true;
	
	}	
	/**Method performing an opening of a new blank text area*/
	public void createNewFile(){
		
		if (checkSaveFile()!= SAVECANCELED){
			
			editorWindow.textArea.replaceRange("",0,editorWindow.textArea.getText().length());
			editorWindow.setModified(false);			
			editorWindow.infoStatus.setText(" New file ");
			editorWindow.setTitle("New Text file - Collaborative TextEditor. Group 4. Soen 6441");
			editorWindow.setNewFile(true);
		}
	}

	/**Method performing opening text file from hard drive*/
	public void openFile(){
		
		if (checkSaveFile()!= SAVECANCELED){
			String line = null;
			JFileChooser fileChooser = new JFileChooser();
			fileChooser.setDialogTitle("Open file");

			FileFilter fileFilter = fChooser.createFileFilter("Text Files",
                    true, "txt");
			fileChooser.setFileFilter(fileFilter);

			int result = fileChooser.showOpenDialog(editorWindow);
			if(result == JFileChooser.CANCEL_OPTION)
			{	
				editorWindow.infoStatus.setText(" Open file is canceled. ");
				return;
			}

				File file = fileChooser.getSelectedFile();
				BufferedReader bfr = null;
			
				try {
				bfr = new BufferedReader(new FileReader(file));
				editorWindow.textArea.setText("");
				while((line=bfr.readLine())!=null)
				{	
					editorWindow.textArea.append(line + "\n");
				}
				editorWindow.textArea.setCaretPosition(0);
			
			} catch (IOException e1) {			
				e1.printStackTrace();
				
			}
			finally{
				try {
					bfr.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
			
			editorWindow.setTitle(file.getName()+ " - Collaborative TextEditor. Group 4. Soen 6441");
			editorWindow.infoStatus.setText(" Current openning file " + file.getAbsoluteFile());

			editorWindow.setNewFile(false);
			editorWindow.setCurrentFile(file);
			editorWindow.setModified(false);
		}
	}
}
